<?php

namespace app\model;

use app\model\fuhai\Markting;
use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class Supplier extends Model
{
    public function appid(): HasOne
    {
        return $this->hasOne(Markting::class, "code", "fuhai_appid");
    }

    public function getPage(): array
    {
        $params = request()->get();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 50;
        $data = $this->when(!empty($params['name']), function ($query) use ($params) {
            $query->whereLike('name|username', '%' . $params['name'] . '%');
        })->when(!empty($params['state']), function ($query) use ($params) {
            $query->where('state', $params['state']);
        })->when(!empty($params['mobile']), function ($query) use ($params) {
            $query->where('mobile', $params['mobile']);
        })->when(!empty($params['id']), function ($query) use ($params) {
            $query->where('id', $params['id']);
        })->where(['is_del' => 1])->order(['create_time' => 'desc'])->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function updateOrAdd(): array
    {
        $param = request()->post();
        $param['content'] = htmlentities($param['content']);
        if (empty($param['start_time'])) {
            $param['start_time'] = date("Y-m-d 00:00:00");
        }
        if (empty($param['end_time'])) {
            $param['end_time'] = date("Y-m-d 23:59:59", strtotime("+1 year"));
        }
        unset($param['create_time'], $param['update_time']);
        $this->startTrans();
        $this->exists(!empty($param['id']))->save($param);
        if (empty($param['id'])) {
            //新增渠道账号
            $account = app(Account::class);
            $password = setPassword("123456");
            $mobile = $account->where(['account' => $param['mobile'], 'is_del' => 1])->count();
            $_account = $param['mobile'];
            if ($mobile > 0) {
                //将字符按长度分割成数组
                $arr = str_split($param['mobile'], 1);
                $_account .= bcadd(bcadd(bcadd($this->pid, 1000), array_sum($arr)), rand(100, 999));
            }
            $insert = [
                'name' => $param['username'],
                'supplier_id' => $this->id,
                'store_id' => 0,
                'type' => 1,
                'balance' => 0,
                'mobile' => $param['mobile'],
                'is_del' => 1,
                'state' => 1,
                'password' => $password['password'],
                'decode' => $password['encode'],
                'account' => $_account
            ];
            $account->save($insert);
        }
        $this->commit();
        return $this->toArray();
    }

    public function detail()
    {
        $id = request()->param("id");
        $data = $this->findOrFail($id);
        $data->content = htmlspecialchars_decode($data->content);
        return $data;
    }

    public function del(): array
    {
        $id = request()->param("id");
        $data = $this->findOrFail($id);
//        if($data->balance > 0) throw new \Exception("预存余额不为0，无法删除",7023);
        $count = app(Store::class)->where(['pid' => $id, 'is_del' => 1])->count();
        if ($count > 0) throw new \Exception("该渠道下有门店，无法删除", 7024);
        $data->startTrans();
        $data->is_del = 0;
        $data->save();
        app(Account::class)->where(['supplier_id' => $id])->save(['is_del' => 0]);
        $data->commit();
        return $data;
    }

    public function supplierSearch(): array
    {
        $admin = request()->admin;
        return $this->where(['is_del' => 1, 'state' => 1])->when(!empty($admin) && $admin['is_admin'] == 2, function ($query) {
            $query->where("id", "<>", 5);
        })->column("id,name");
    }
}
